package com.example.logging.Aspect;

import com.example.common.Utils.JwtUtil;
import com.example.logging.Service.ILoggerService;
import com.example.user.bean.Log;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import springfox.documentation.RequestHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/11/2-11-02-17:08
 * @Description：com.example.cms.Aspect
 */
@Aspect
@Component
public class LogAspect {
    @Autowired
    private ILoggerService service;
    //切入点
    @Pointcut("execution(* com.example..web.Controller.*.*(..)) && @annotation(com.example.logging.anno.LoggingAccess)")
    public void pointcut(){}

    //环绕通知
    @Around("pointcut()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();

        String token = request.getHeader("Authorization");
        Map<String, Object> info = JwtUtil.getInfo(token);
        Log log = Log.builder()
                .logUsername((String)info.get("username"))
                .logRealname((String)info.get("realname") )
                .logRequestMethod(request.getMethod())
                .logRequestUri(request.getRequestURI())
                .logTime(new Date())
                .build();
        //增强目标方法
        service.add(log);
        //目标方法执行
        return pjp.proceed(pjp.getArgs());
    }
}
